<template lang="pug">
  master-layout
    div.login-w(slot="main")
      logo.logo
      div.instructions
        br
        | 使用指南：
        br
        | 1.请考生填写本人：“身份证号”信息，确认无误后点击“登录”。
        br
        | 2.登录后请严格按照界面提示进行答题。
      div.form-w
        div.form-w--mn
          el-form.kalix-form(v-bind:model="loginForm" v-bind:rules="rules" ref="loginForm" v-bind:show-message="false" label-width="90px")
            div.error-message {{error.message}}
            el-form-item.kalix-form-item(prop="name" label="身份证号 :")
              el-input(v-model="loginForm.name" v-on:keyup="" placeholder="请输入身份证号" ref="loginFormName")
                i.icon-users(slot="prefix")
            el-form-item.kalix-form-item(prop="pass" label="密码 :")
              el-input(type="password" v-model="loginForm.pass" ref="loginFormPass" placeholder="请输入密码" auto-complete="off")
                i.icon-lock(slot="prefix")
            el-form-item(label="")
              el-button.kalix-form--button(@click="onSubmit")
      div.c(v-if="false")
        handwriting-board(@confirm="onHConfirm")
      face-recognise(v-if="showFaceRecognise" v-bind:photoSaveName="photoSaveName"
        @photographed="handlerCameraPhotographed")
</template>

<script type="text/ecmascript-6">
  import MasterLayout from '../layout/Master'
  import Logo from '../components/Logo'
  import Login from '../api/login'
  import {mapActions} from 'vuex'
  import fs from 'fs'
  import Electrom from 'electron'
  import HandwritingBoard from '../components/HandwritingBoard'
  import Camera from '../components/Camera'
  import FaceRecognise from '../components/FaceRecognise'
  import zipdir from 'zip-dir'

  //  import nodeCmd from 'node-cmd'

  export default {
    data() {
      return {
        loginForm: {
          name: '',
          pass: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入身份证号', trigger: 'blur'},
            {min: 0, max: 18, message: '用户名长度在 15 到 18 个字符', trigger: 'blur'}
          ],
          pass: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ]
        },
        error: {
          flag: false,
          message: ''
        },
        folderName: null,
        materialFolderUrl: null,
        zipFileName: '1234567',
        zipFileNameExt: '.zip',
        examId: null,
        canvasWidth: 400,
        canvasHeight: 300,
        showFaceRecognise: false,
        photoSaveName: ''
      }
    },
    components: {
      MasterLayout,
      Logo,
      HandwritingBoard,
      Camera,
      FaceRecognise
    },
    mounted() {
      this.$nextTick(() => {
        this.determineScreenShotSize()
        clearTimeout(window.mtCheckTime)
      })
    },
    methods: {
      ...mapActions([
        'setSubject',
        'setFolderUrl',
        'setStudentInfo',
        'setUserLoginName',
        'setScreenShotSize'
      ]),
      determineScreenShotSize() {
        const electronScreen = Electrom.screen
        const screenSize = electronScreen.getPrimaryDisplay().workAreaSize
        const maxDimension = Math.max(screenSize.width, screenSize.height)
        this.setScreenShotSize({
          width: maxDimension * window.devicePixelRatio,
          height: maxDimension * window.devicePixelRatio
        })
      },
      /**
       * 拍照
       */
      async onPhotograph() {
        await this.$refs.camera.handlerPhotograph(`1111-2222`)
      },
      /**
       * 拍照完成
       */
      handlerCameraPhotographed() {
        this.showFaceRecognise = false
        this.dirClear()
      },
      onUploadFile() {
        this.zipFileName = 'examFile.zip'
        let _path = `D:\\examtemp\\1000`
        let files = fs.readdirSync(_path)
        if (files.length === 0) {
          fs.mkdirSync(`${_path}\\1000`)
        }
        setTimeout(() => {
          zipdir(_path, {saveTo: `${_path}\\${this.zipFileName}`}, (err, buffer) => {
            console.log('zipdir err', err)
          })
        }, 200)
      },
      onHConfirm(res) {
        console.log('res', res)
      },
      /**
       * 提交表单
       */
      async onSubmit() {
        clearTimeout(window.mtAutoCloseExam)
        const uploadFile = `${__static}\\uploadFiles\\`
        this.deleteDir(uploadFile).then(() => {
          fs.mkdirSync(uploadFile)
          if (this._validateForm()) {
            this.login()
          }
        })
      },
      deleteDir(path) {
        return new Promise(resolve => {
          let files = []
          if (fs.existsSync(path)) {
            files = fs.readdirSync(path)
            files.forEach((file, index) => {
              let curPath = path + '/' + file
              if (fs.statSync(curPath).isDirectory()) {
                this.deleteDir(curPath) // 递归删除文件夹
              } else {
                fs.unlinkSync(curPath) // 删除文件
              }
            })
            fs.rmdirSync(path)
          }
          resolve()
        })
      },
      /**
       * 登录提示
       * @param text
       * @param lock
       * @returns {*}
       */
      loadingTools(text, lock = true) {
        return this.$loading({
          lock,
          text,
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.4)'
        })
      },
      /**
       * 登录
       */
      async login() {
        let l1 = this.loadingTools('登录授权')
        //  登录
        let data = await Login.remoteLogin({
          'username': this.loginForm.name,
          'password': this.loginForm.pass
        })
        l1.close()
        if (data.success) {
          this.stuId = data.user.id
          this.$KalixCatch.save('id', this.stuId)
          this.$KalixCatch.save('access_token', data.access_token)
          this.$KalixCatch.save('user_token', data.user.token)
          this.$KalixCatch.save('user_name', data.user.name)
          this.$KalixCatch.save('loginname', this.loginForm.name)
          // 在缓存中记录最后登录时间，处理单用户登录需求
          let now = new Date().getTime()
          this.$KalixCatch._saveLocal('lastLoginTime', now)
          this.$KalixCatch.save('lastLoginTime', now)
          data.user.loginname = this.loginForm.name
          this.$KalixCatch.save('setCurrentUser', JSON.stringify(data.user))
          let appConfig = Electrom.remote.getGlobal('appConfig')
          appConfig.currentUser = data.user
          appConfig.accessToken = data.access_token
          appConfig.userToken = data.user.token
          // this.$router.push({name: 'StudentInfo'})
          // console.log('\'[ ===== 2019年3月7日14:03:16 ===== ] Login OK!')

          let l2 = this.loadingTools('核对信息')
          let stuErr = await this.getSutdentInfo()
          l2.close()
          if (stuErr) {
            this.$alert('目前没有考试！', '消息', {
              callback: action => {
                this.$refs['loginForm'].resetFields()
              }
            })
            return
          }
          this.materialFolderUrl = `${window.KalixConfig.materialFolder + this.folderName}`
          // console.log('\'[ ===== 2019年3月7日14:03:16 ===== ] Get Student Info OK!')
          // 拍照
          // await this.$refs.camera.handlerPhotograph(`${this.examId}-${this.loginForm.name}-${new Date().getTime()}`)
          this.photoSaveName = `${this.examId}-${this.loginForm.name}`
          this.setUserLoginName(this.loginForm.name)
          this.$nextTick(() => {
            this.showFaceRecognise = true
          })
        } else {
          this.$refs.loginFormName.focus()
          this.$KalixMessage.error(data.message)
        }
      },
      /**
       * 验证表单
       */
      _validateForm() {
        //  验证表单
        for (let key in this.rules) {
          this.error.flag = false
          this.error.message = ''
          this.$refs.loginForm.validateField(key, errorMessage => {
            //  如果错误信息长度 > 0 表示验证不通过
            this.error.flag = errorMessage.length > 0
            this.error.message = errorMessage
          })
          setTimeout(() => {
            this.error.message = ''
          }, 1500)
          if (this.error.flag) {
            return false
          }
        }
        return true
      },
      // 获取学生信息
      getSutdentInfo() {
        return new Promise(async resolve => {
          let {status, data: {totalCount, data}} = await this.$http.get('/camel/rest/examings/examineeuser', {
            params: {
              userId: this.stuId
            }
          })
          console.log('data', data)
          if (status === 200 && totalCount > 0) {
            let {examTimeStr, subject, userName, idCards, examDateStr, examId, paperId, quesIds, examStart, examEndTime, duration} = data[0]
            console.log('subject:', subject)
            this.$KalixCatch.save('STUDENT_INFO', JSON.stringify({
              stuId: this.stuId,
              loginName: this.loginForm.name,
              examTimeStr,
              subject,
              userName,
              idCards,
              examId,
              paperId,
              quesIds,
              examDateStr, // 考试日期
              examStart, // 考试开始时间
              examEndTime, // 考试结束时间
              duration // 考试时长
            }))
            this.zipFileName = quesIds
            this.folderName = subject
            this.examId = examId
            resolve()
          } else {
            resolve(new Error('操作失败'))
          }
        })
      },
      /**
       * 清理资源目录
       */
      clearMaterialFolder() {
        // nodeCmd.get(`rmdir /s/q ${window.KalixConfig.materialFolder}`)
        // this.dirClear()
        const uploadFilePath = `${__static}\\uploadFiles\\`
        fs.readdir(uploadFilePath, (err, files) => {
          if (err) {
            // console.log('没有指定文件夹')
            this.dirClear()
            return
          }
          // console.log('files', files)
          this._files = files.filter(item => {
            return item !== this.folderName
          })
          // console.log('_files', this._files)
          this.delDirEnd()
        })
      },
      delDir(path) {
        let files = []
        if (fs.existsSync(path)) {
          files = fs.readdirSync(path)
          files.forEach((file, index) => {
            let curPath = path + '/' + file
            if (fs.statSync(curPath).isDirectory()) {
              this.delDir(curPath) // 递归删除文件夹
            } else {
              fs.unlinkSync(curPath) // 删除文件
            }
          })
          fs.rmdirSync(path)
          this.delDirEnd()
        } else {
          this.delDirEnd()
        }
      },
      delDirEnd() {
        console.log('this._files.length', this._files.length)
        if (this._files.length) {
          this.delDir(`${window.KalixConfig.materialFolder + this._files.pop()}`)
        } else {
          this.dirClear()
        }
      },
      /**
       * 清理文件夹
       * @returns {Promise<void>}
       */
      async dirClear() {
        this.$router.replace('/student-info')
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">

  .login-w
    width 637px
    margin 0 auto

    .logo
      margin-top 111px

    .instructions
      color #ff0000
      font-size 14px
      line-height 24px
      margin-top 50px

    .form-w
      height 242px
      overflow hidden
      margin-top 48px
      background url("../assets/images/login-form-bg.png") 0 0 no-repeat

    .kalix-form
      width 350px
      margin 22px auto 0

      .error-message
        font-size 14px
        color #ff0000
        text-align right
        line-height 14px
        height 14px
        margin-bottom 6px

      .kalix-form--button
        border 0
        width 137px
        height 30px
        background url("../assets/images/submit-button-bg.png") 0 0 no-repeat

  .c
    position absolute
    top 0
    left 0

  .c-2
    position absolute
    top 0
    left 0
    width auto
    height auto
</style>
